package com.fc.advbox.process.migrate.dialects;

import com.fc.advbox.process.migrate.Migrator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * dialect for the mysql database.
 * 
 * @author Chris
 */
public class MySQLDialect extends AbstractDialect {

    private static final Logger LOG = LoggerFactory.getLogger(MySQLDialect.class);

    /**
     * @see com.fc.advbox.process.migrate.Dialect#createVersionTable(Connection, String)
     */
    @Override
    public void createVersionTable(Connection conn, String versionTable) throws SQLException {
        try {
            super.createVersionTable(conn, versionTable);
        } catch (SQLException e ) {
            LOG.debug( "sql exception '%s' occured, assuming it's because of duplicate table creation", e.getMessage() );
        }
    }


    /**
     * @see com.fc.advbox.process.migrate.Dialect#hasVersionTable(Connection, String)
     */
    @Override public boolean hasVersionTable(Connection conn, String versionTable) throws SQLException {
        // for this assume it's always no, and then catch the exception, hsql provides no
        // means to test for table existence.
        return false;
    }
    
    /**
     * @see com.fc.advbox.process.migrate.Dialect#executeSql(Connection, String)
     */
    @Override public void executeSql(Connection conn, String sql) throws SQLException {
        Statement ps = conn.createStatement();
        if ( sql.length() > Migrator.SQL_LENGTH_LIMIT ) {
            throw new SQLException("SQL is too long: Allowed Length: [" + Migrator.SQL_LENGTH_LIMIT + "] Actual Length: [" + sql.length() + "]");
        } else {
            ps.executeUpdate(sql);
        }
        ps.close();
    }


}
